package com.wn.budget.controller;

import com.wn.budget.model.ProjectSpace;
import com.wn.budget.repository.ProjectSpaceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author lin yue bin
 * @version 1.0
 * @date 2019/10/19 22:11
 */
@RestController
@RequestMapping(value = "projectSpace")
public class ProjectSpaceController {
    @Autowired
    ProjectSpaceRepository projectSpaceRepository;

    @PostMapping("insert")
    public boolean insert(HttpServletRequest request, ProjectSpace project) {
        project.setId(UUID.randomUUID().toString());
        project.setCreateDate(new Date());

        projectSpaceRepository.saveAndFlush(project);
        return true;
    }

    @PostMapping("update")
    public boolean update(ProjectSpace project) {
        projectSpaceRepository.saveAndFlush(project);
        return true;
    }

    @GetMapping("findById")
    public ProjectSpace findById(@RequestParam("id") String id) {
        return projectSpaceRepository.findById(id).get();
    }

    @GetMapping("deleteById")
    public void deleteById(@RequestParam("id") String id) {
        projectSpaceRepository.deleteById(id);
    }

    @GetMapping("findAll")
    public List<ProjectSpace> findAll(HttpServletRequest request, @RequestParam("projectId") String projectId) {
        List<ProjectSpace> list = projectSpaceRepository.findByProjectIdOrderBySortDesc(projectId);
        return list;
    }

    /**
     * 空间排序
     */
    @PostMapping("sortProjectSpace")
    public boolean sortProjectSpace(ProjectSpace projectA, ProjectSpace projectB) {
        ProjectSpace a = projectSpaceRepository.getOne(projectA.getId());
        ProjectSpace b = projectSpaceRepository.getOne(projectB.getId());
        a.setSort(projectA.getSort());
        b.setSort(projectB.getSort());
        projectSpaceRepository.saveAndFlush(a);
        projectSpaceRepository.saveAndFlush(b);
        return true;
    }
}
